<template>
    <div class="app-container">
        <FilterSearch v-show="showSearch" class="filter-search" :value="queryParams" :config="configData">
        </FilterSearch>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        <el-table v-loading="loading" :data="dataList" @selectionChange="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column type="index" label="序号" minWidth="60">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="账号" align="center" prop="username" />
            <el-table-column label="用户昵称" align="center" prop="nickname" />
            <el-table-column label="真实姓名" align="center" prop="realName" />
            <el-table-column label="部门" align="center" prop="deptName" />
            <el-table-column prop="postName" label="岗位" align="center" minWidth="120" />
            <el-table-column label="手机号码" align="center" prop="phone" minWidth="120" />
            <el-table-column label="邮箱" align="center" prop="email" minWidth="120" />
            <el-table-column label="头像" align="center" prop="phone" minWidth="120">
                <template #default="scope">
                    <el-avatar
                        :src="scope.row.imageList && scope.row.imageList.length > 0 ? scope.row.imageList[0] : ''"></el-avatar>
                </template>
            </el-table-column>
            <el-table-column prop="gender" label="性别" minWidth="80">
                <template #default="scope">
                    {{ scope.row.gender == 'M' ? '男' : '女' }}
                </template>
            </el-table-column>
            <el-table-column prop="roleNames" label="角色" minWidth="120">
            </el-table-column>
            <el-table-column label="状态" align="center">
                <template #default="scope">
                    <dict-tag :options="statusOptions" :value="scope.row.status"></dict-tag>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" :show-overflow-tooltip="true" minWidth="200"></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
                <template #default="scope">
                    <span>{{ scope.row.createTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                <template #default="scope">

                    <el-button v-hasPermi="['permission:user:edit']" link type="primary" icon="Edit"
                        @click="handleEdit(scope.row)">编辑</el-button>

                    <el-button v-hasPermi="['permission:user:remove']" link type="primary" icon="Delete"
                        @click="handleRemove(scope.row)">删除</el-button>

                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
            :total="total" @pagination="getList" />

        <!-- 添加或编辑用户配置对话框 -->
        <el-dialog v-model="open" :title="title" width="800px" append-to-body>
            <el-form ref="userRef" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户账号" prop="username">
                            <el-input v-model="form.username" clearable placeholder="请输入用户账号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="用户昵称" prop="nickname">
                            <el-input v-model="form.nickname" clearable placeholder="请输入用户昵称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="用户姓名" prop="realName">
                            <el-input v-model="form.realName" clearable placeholder="请输入用户姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="归属部门">
                            <el-input v-model="form.deptName" clearable placeholder="请输入归属部门" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="岗位">
                            <el-input v-model="form.postName" clearable placeholder="请输入岗位" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号码">
                            <el-input v-model="form.phone" clearable placeholder="请输入手机号码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱">
                            <el-input v-model="form.email" clearable placeholder="请输入用户邮箱" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="角色">
                            <el-select v-model="form.roleIds" clearable multiple filterable placeholder="请选择角色"
                                class="el-select">
                                <el-option v-for="(item, index) in formList.roleOptions" :label="item.roleName"
                                    :value="item.id" :key="index"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别">
                            <el-radio-group v-model="form.gender">
                                <el-radio :label="item.value" v-for="(item, index) in formList.genderOptions"
                                    :key="index">{{
                                        item.label
                                    }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态">
                            <el-radio-group v-model="form.status">
                                <el-radio :label="item.value" v-for="(item, index) in statusOptions" :key="index">{{
                                    item.label
                                }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="头像" prop="images">
                            <ImageUpload v-model="form.imageList" :limit="1" uploadImgUrl="/file/user/uploadPic" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" rows="3" resize="none" type="textarea"
                                placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="User" lang="ts">
/* eslint-disable camelcase */
import {
    userList,
    userRemove,
    userEdit,
    userAdd,
} from '@/api/permission/user';
import { roleListAll } from "@/api/permission/role";
import { getCurrentInstance, ComponentInternalInstance, ref, reactive, toRefs, computed, Ref, ComponentPublicInstance } from 'vue';
import { statusOptions, genderOptions, OptionItem } from "@/constant";
import { encrypt } from '@/utils/jsencrypt';

// 定义用户数据接口
interface UserItem {
    id?: number;
    username?: string;
    nickname?: string;
    realName?: string;
    deptName?: string;
    postName?: string;
    phone?: string;
    email?: string;
    gender?: string;
    status?: number;
    remark?: string;
    roleIds?: number[];
    imageList?: string[];
    createTime?: string;
    roleNames?: string;
    [key: string]: any;
}

// 定义角色选项接口
interface RoleOption {
    id?: number;
    roleName?: string;
    [key: string]: any;
}

// 定义表单引用类型
type FormInstance = ComponentPublicInstance & {
    validate: (callback: (valid: boolean) => void) => void;
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dataList = ref<UserItem[]>([]);
const open = ref(false);
const loading = ref(true);

const total = ref(0);
const title = ref('');
const showSearch = ref<boolean>(true);
// 定义表单验证规则类型
interface FormRules {
    userName?: any[];
    nickName?: any[];
    email?: any[];
    phonenumber?: any[];
}

const data = reactive({
    form: {} as UserItem,
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined as string | undefined,
        phonenumber: undefined as string | undefined,
        status: undefined as number | undefined,
        deptId: undefined as number | undefined,
    },
    rules: {
        username: [
            { required: true, message: '用户名称不能为空', trigger: 'blur' },
            { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' },
        ],
        nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
        email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
        phone: [
            { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' },
        ],
    } as FormRules,
});

const formList = reactive({
    roleOptions: [] as RoleOption[],
    genderOptions: genderOptions as OptionItem[]
});

const handleChecked = reactive<{
    ids: number[],
    multiple: boolean
}>({
    ids: [],
    multiple: true
});

const { queryParams, form, rules } = toRefs(data);
const { ids, multiple } = toRefs(handleChecked);
const configData = computed(() => {
    let config = {
        itemConfig: [
            {
                type: "input",
                prop: "name",
                label: "用户名称",
                placeholder: "请输入"
            },
            {
                type: "input",
                prop: "phone",
                label: "手机号",
                placeholder: "请输入"
            },
            {
                type: "select",
                prop: "status",
                label: "状态",
                placeholder: "请选择",
                optList: statusOptions
            },
            {
                type: "datetimerange",
                prop: "createTime",
                label: "创建时间",
                dateFormate: "YYYY-MM-DD HH:mm:ss",
                placeholder: "请选择"
            },
        ],
        operate: [
            {
                icon: "Search",
                type: "primary",
                name: "查询",
                handleClick: getList,
                rule: false,
            },
            {
                icon: "RefreshRight",
                type: "info",
                name: "重置",
                handleClick: reset,
                rule: false,
            },
            {
                icon: "Plus",
                type: "success",
                name: "新增",
                handleClick: add,
                rule: false,
                disabled: !proxy!.$auth?.hasPermi("permission:user:add")
            },
            {
                icon: "Delete",
                type: "danger",
                name: "删除",
                handleClick: remove,
                rule: false,
                disabled: multiple.value
            }
        ],
        rules: {},
    };
    return config;
});

/** 查询用户列表 */
function getList() {
    loading.value = true;
    userList(queryParams.value).then((res: any) => {
        loading.value = false;
        dataList.value = res.data.rows as UserItem[];
        total.value = res.data.total as number;
    });
}

function getOptions() {
    roleListAll().then((res: any) => {
        formList.roleOptions = res.data as RoleOption[];
    })
}

/** 删除按钮操作 */
function remove(row: any) {
    proxy!.$modal
        .confirm('是否确认删除用户编号为"' + ids.value + '"的数据项?')
        .then(function () {
            return userRemove(ids.value);
        })
        .then((res: any) => {
            getList();
            proxy!.$modal.msgSuccess(res.msg);
        });
}

/** 删除按钮操作 */
function handleRemove(row: UserItem) {
    const userIds = row.id || ids.value;
    proxy!.$modal
        .confirm('是否确认删除用户名称为"' + row.username + '"的数据项？')
        .then(function () {
            return userRemove([userIds]);
        })
        .then((res: any) => {
            getList();
            proxy!.$modal.msgSuccess(res.msg);
        })
        .catch((e: any) => {
            console.log(e);
        });
}

/** 选择条数  */
function handleSelectionChange(selection: UserItem[]) {
    ids.value = selection.map(item => item.id as number);
    if (ids.value.length > 0) {
        if (proxy!.$auth?.hasPermi("permission:user:remove")) {
            multiple.value = false
        }
    } else {
        multiple.value = true;
    }
}

/** 重置操作表单 */
function reset() {
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
    };
    getList();
}

/** 取消按钮 */
function cancel() {
    const userFormRef = proxy?.$refs['userRef'] as FormInstance | undefined;
    if (userFormRef?.resetFields) {
        userFormRef.resetFields();
    }
    open.value = false;
}

/** 新增按钮操作 */
function add() {
    title.value = '添加用户';
    open.value = true;

}

/** 编辑按钮操作 */
function handleEdit(row: UserItem) {
    form.value = {
        id: row.id,
        username: row.username,
        nickname: row.nickname,
        realName: row.realName,
        deptName: row.deptName,
        postName: row.postName,
        imageList: row.imageList,
        phone: row.phone,
        email: row.email,
        roleIds: row.roleIds,  // 新增的角色ID
        gender: row.gender,
        status: row.status,
        remark: row.remark
    };
    title.value = '编辑用户';
    open.value = true;
}

/** 提交按钮 */
function submitForm() {
    const userFormRef = proxy?.$refs['userRef'] as FormInstance | undefined;
    userFormRef?.validate((valid: boolean) => {
        if (valid) {
            if (form.value.id) {
                userEdit(form.value).then((res: any) => {
                    proxy!.$modal.msgSuccess(res.msg);
                    cancel();
                    getList();
                });
            } else {
                let params = {
                    ...form.value,
                    password: encrypt('123456')
                }
                userAdd(params).then((res: any) => {
                    proxy!.$modal.msgSuccess(res.msg);
                    cancel();
                    getList();
                });
            }
        }
    });
}

getList();
getOptions();
</script>

<style scoped lang="scss">
.el-select {
    width: 100%;
}
</style>